<template>
  <div class="form-wrapper">
    <Form
      ref="baseForm"
      :model="baseForm"
      :rules="ruleValidate"
      :label-position="labelPosition"
      :label-width="labelWidth"
    >
      <fieldset class="line-field">
        <legend>课程基本信息</legend>
        <FormItem label="所属学院" prop="institute">
          <Input v-model="baseForm.institute" readonly placeholder="教师所属学院" />
        </FormItem>
        <FormItem label="教师姓名" prop="teacher_name">
          <Input v-model="baseForm.teacher_name" readonly placeholder="教师姓名" />
        </FormItem>
        <FormItem label="课程" prop="course_name">
            <Input v-model="baseForm.course_name" placeholder="课程" />
        </FormItem>
        <FormItem label="实验教材" prop="textbook">
          <Input type="textarea" v-model="baseForm.textbook" clearable placeholder="实验指导书名称，编(写)者，出版社，出版日期" :autosize="{minRows: 2, maxRows: 6}"></Input>
        </FormItem>
        <FormItem label="实训对象" class="ivu-form-item-required">
          <Row :gutter="20" type="flex" justify="space-between" style="margin-bottom: 15px;"
            v-for="(classesItem, classesIndex) in baseForm.classes"
            :key="classesItem.guid">
            <Col span="2" class="pl-15">年级：</Col>
            <Col span="5">
              <FormItem :prop="'classes.' + classesIndex + '.grade'" :rules="ruleValidate.grade">
                <Select :enabledPreventOverflow="enabledPreventOverflow" v-model="classesItem.grade"
                        placeholder="请选择年级" filterable @on-change="onChangeGrade(classesIndex)">
                  <Option v-for="(option, index) in options.grade" :value="option" :key="index">{{ option }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="2" class="pl-15">专业：</Col>
            <Col span="7">
              <FormItem :prop="'classes.' + classesIndex + '.major'" :rules="ruleValidate.major">
                <Select :enabledPreventOverflow="enabledPreventOverflow"
                        v-model="classesItem.major"
                        :placeholder="baseForm.institute ? (classesItem.grade ? '请选择专业' : '请先选择年级') : '请先选择学院'"
                        filterable clearable
                        :disabled="!(baseForm.institute && classesItem.grade)">
                  <Option v-for="(option, index) in classesItem.major_options" :value="option" :key="index">{{ option }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="7" class="text-right">
              <Poptip
                  confirm
                  title="确认删除该实训对象吗？"
                  @on-ok="remove_teach_obj(classesIndex)"
                  v-if="!(classesIndex === 0 && baseForm.classes.length === 1)"
                  :options="popperOpts"
                  class="text-left">
                <Tooltip content="删除该实训对象">
                  <Button type="warning" shape="circle" icon="md-trash"></Button>
                </Tooltip>
              </Poptip>
              <Tooltip content="新增实训对象"
                      v-if="classesIndex + 1 === baseForm.classes.length"
                      style="margin-left: 1.5em">
                <Button type="info" shape="circle" icon="md-add"
                        @click="add_teach_obj"></Button>
              </Tooltip>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="人数" prop="stu_num">
            <InputNumber :min="1" v-model="baseForm.stu_num" placeholder="总人数" style="width: 220px"></InputNumber>
        </FormItem>
        <!-- <FormItem label="人数" prop="stu_num">
            <InputNumber :min="1" v-model="baseForm.stu_num" placeholder="总人数" style="width: 220px"></InputNumber>
        </FormItem> -->
      </fieldset>
    </Form>
    <div id="actions" class="text-center position-relative">
      <Poptip
        confirm
        title="确定修改该申请表的课程基本信息吗？"
        word-wrap
        width="180"
        @on-ok="handleSave"
        class="text-left"
        :options="popperOpts"
      >
        <Button type="success" :loading="loading.submit" class="mr-20">
          <span v-if="!loading.submit">提交表单</span>
          <span v-else>提交中...</span>
        </Button>
      </Poptip>
      <Poptip
        confirm
        title="数据将不可恢复，确定重置表单吗？"
        word-wrap
        width="180"
        @on-ok="handleReset"
        class="text-left"
        :options="popperOpts"
      >
        <Button style="margin-left: 8px" :disabled="loading.submit">重置表单</Button>
      </Poptip>
    </div>
  </div>
</template>
<script>
import { generateGuid } from '@/libs/tools'
import { getMajorByGradeAndInstitute, getFormDetailByCode, updateTrainingBase } from '@/api/apply-form'
export default {
  name: 'SaveTrainingBase',
  data () {
    return {
      loading: {
        submit: false
      },
      options: {
        grade: []
      },
      baseForm: {
        app_code: null,
        exp_type: 'TRAINING',
        institute: null,
        teacher_name: null,
        course_name: null,
        textbook: null,
        classes: [{
          guid: generateGuid(),
          grade: null,
          major: null,
          major_loading: false,
          major_options: []
        }],
        stu_num: null
      },
      ruleValidate: {
        institute: [
          {required: true, message: '学院不能为空', trigger: 'change'}
        ],
        teacher_name: [
          {required: true, message: '教师不能为空', trigger: 'change'}
        ],
        course_name: [
          {required: true, message: '课程名字不能为空', trigger: 'change'}
        ],
        grade: [
          {required: true, type: 'number', message: '年级不能为空', trigger: 'change'}
        ],
        major: [
          {required: true, message: '专业不能为空', trigger: 'change'}
        ],
        textbook: [
          {required: true, message: '实验教材详细情况不能为空', trigger: 'blur'}
        ],
        classes: [
          {required: true, type: 'array', min: 1, message: '至少选择一个班级', trigger: 'change'}
        ]
      },
      // 原子实验项目数据
      oriData: null,
      labelPosition: 'left',
      labelWidth: 100,
      // 全选班级的 indeterminate 状态，只负责样式控制
      classesIndeterminate: false,
      // 班级是否全选
      classesCheckAll: false,
      // Select选择器的下拉列表是否吸附，默认为true，吸附
      enabledPreventOverflow: false,
      popperOpts: {
        modifiers: {
          preventOverflow: {
            // 边界元素: scrollParent, window, viewport or any DOM element. 默认iview默认window
            boundariesElement: 'scrollParent'
          }
        }
      }
    }
  },
  props: {
    app_code: {
      type: String,
      default: null
    }
  },
  methods: {
    getCurrentGrades (date = new Date()) {
      // getYear获取的时间如果小于1900,那就要加上1900
      // 比如 2017 ,getYear获取的时间就是117,加上1900就是2017
      let current = {
        year: (date.getYear() < 1900) ? (1900 + date.getYear()) : date.getYear(),
        month: date.getMonth() + 1
      }
      if (current.month < 8) {
        this.options.grade = [
          current.year - 4,
          current.year - 3,
          current.year - 2,
          current.year - 1
        ]
      } else {
        this.options.grade = [
          current.year - 3,
          current.year - 2,
          current.year - 1,
          current.year - 0
        ]
      }
    },
    // 改变年级的回调函数
    async onChangeGrade (index) {
      let classItem = this.baseForm.classes[index]
      let institute = this.baseForm.institute
      classItem.major = ''
      if (institute && classItem.grade) {
        classItem.major_loading = true
        classItem.major_options = await this.getMajorOptions(classItem.grade)
        classItem.major_loading = false
        if (classItem.major_options.length < 1) {
          this.$Notice.error({
            title: '抱歉',
            desc: classItem.grade + '级' + this.baseForm.institute + '下暂无专业，请选择其他年级。'
          })
        }
      }
    },
    // 获取专业列表
    async getMajorOptions (grade) {
      let institute = this.baseForm.institute
      try {
        let res = await getMajorByGradeAndInstitute(grade, institute)
        res = res.data
        if (res.code && res.data.length > 0) {
          return res.data
        } else {
          return []
        }
      } catch (error) {
        return []
      }
    },
    // 增加实训对象
    add_teach_obj (value) {
      this.baseForm.classes.push({
        guid: generateGuid(),
        grade: null,
        major: null,
        major_loading: false,
        major_options: []
      })
    },
    // 删除实训对象
    remove_teach_obj (index) {
      this.baseForm.classes.splice(index, 1)
    },
    // 通过appCode获取历史申请表的详细信息
    async getPastFormByCode (code) {
      try {
        let res = await getFormDetailByCode(code)
        res = res.data
        if (res.code) {
          let formData = res.data
          try {
            this.fillFormByData(formData)
          } catch (error) {
            this.$Spin.hide()
            this.$emit('failFillFrom', '抱歉，获取登记表信息失败，请刷新后重试。' + error)
          }
        } else {
          this.$Spin.hide()
          this.$emit('failFillFrom', '抱歉，获取登记表信息失败，请刷新后重试。' + res.info)
        }
      } catch (error) {
        this.$Spin.hide()
        this.$emit('failFillFrom', '抱歉，获取登记表信息失败，请刷新后重试。' + error)
        console.log(error)
      }
    },
    // 通过从后台获取的数据填充到当前表单中
    async fillFormByData (data) {
      delete data.expBaseInfoItems
      delete data.teacher_code
      delete data.course_code
      this.baseForm.institute = data.institute
      // 处理实训对象数据，要加上major_options，如果不加，后期再新增，会检测不到数据变化
      for (let i = 0; i < data.classes.length; i++) {
        let item = data.classes[i]
        item.guid = generateGuid()
        try {
          item.major_loading = true
          item.major_options = await this.getMajorOptions(item.grade)
          item.major_loading = false
        } catch (error) {
          console.log(error)
          item.major_options = []
          item.major_loading = false
          this.$Notice.error({
            title: '获取' + this.baseForm.institute + item.grade + '级专业列表失败，请稍后重试',
            desc: error.stack
          })
        }
        if (this.options.grade.indexOf(item.grade) < 0) {
          this.options.grade.push(item.grade)
        }
      }
      this.baseForm = JSON.parse(JSON.stringify(data))
      this.oriData = JSON.parse(JSON.stringify(data))
      this.$nextTick(() => {
        this.$Spin.hide()
      })
    },
    // 保存 新增/修改的单个实验
    handleSave () {
      this.loading.submit = true
      this.$refs['baseForm'].validate(async (valid) => {
        if (valid) {
          this.showSpinWithTip('提交表单中，请稍等...')
          try {
            let data = JSON.parse(JSON.stringify(this.baseForm, function (key, value) {
              if (key === 'major_loading' || key === 'major_options' || key === 'guid') {
                return undefined
              } else {
                return value
              }
            }))
            let response = await updateTrainingBase(JSON.stringify(data))
            let res = response.data
            if (res.code) {
              this.$emit('saveSuccess')
            } else {
              this.$Notice.error({
                title: '抱歉，修改申请表课程基本信息失败',
                desc: res.info
              })
            }
          } catch (error) {
            console.log(error)
            this.$Notice.error({
              title: '提交失败',
              desc: '抱歉，修改申请表课程基本信息失败。' + error
            })
          }
          this.$Spin.hide()
        } else {
          this.$Notice.error({
            title: '提交失败',
            desc: '抱歉，无法提交，请先完善表单信息再提交。'
          })
        }
      })
      this.loading.submit = false
    },
    // 重置表单
    handleReset () {
      this.$refs['baseForm'].resetFields()
      this.resetFormData()
    },
    resetFormData () {
      this.baseForm = JSON.parse(JSON.stringify(this.oriData))
    },
    // 显示带文字提示的Spin
    showSpinWithTip (tip) {
      this.$Spin.show({
        render: h => {
          return h('div', { class: 'ivu-spin-large' }, [
            h('span', {
              class: 'ivu-spin-dot',
              style: {
                display: 'inline-block'
              }
            }),
            h('div', tip)
          ])
        }
      })
    }
  },
  created: function () {
    this.getCurrentGrades()
  },
  mounted: function () {
    // 全局配置Notice组件的属性
    this.$Notice.config({
      top: window.innerHeight / 3
    })
    this.showSpinWithTip('加载申请表课程信息中...')
    this.getPastFormByCode(this.app_code)
  },
  beforeDestroy () {
    this.$Notice.destroy()
    this.$Modal.remove()
  }
}
</script>
